#include "databuffer.h"

#include <cstring>
#include <QDebug>

using namespace std;
DataBuffer::DataBuffer(int size)
{
    this->m_max_size = size;
}

DataBuffer::~DataBuffer(){
    m_data.clear();
}

void DataBuffer::cacheData(unsigned int ts, int seq, unsigned char *data, int len){
    if(m_data.find(ts) == m_data.end()){
        m_data[ts] = map< int, vector<unsigned char> >();
        m_ts_queue.push(ts);
        while(m_data.size() > m_max_size ){
            unsigned int _ts = m_ts_queue.front();
            m_data.erase(_ts);
            m_ts_queue.pop();
        }
    }
    if(m_data[ts].find(seq) == m_data[ts].end()){
        m_data[ts][seq] = vector<unsigned char>();
        m_data[ts][seq].resize(len);
        memcpy(&m_data[ts][seq][0], data, len);
    }
}

int DataBuffer::getCount(unsigned int ts){
    if(m_data.find(ts) == m_data.end()){
        return -1;
    }else{
        return m_data[ts].size();
    }
}

bool DataBuffer::has(unsigned int ts, int seq){
    if(m_data.find(ts) == m_data.end()){
        return false;
    }else{
        return( m_data[ts].find(seq) == m_data[ts].end() ? false:true);
    }
}

int DataBuffer::getData(unsigned int ts, int seq, unsigned char *data, int offset){
    if(m_data.find(ts) == m_data.end()){
        return -1;
    }else{
        if(m_data[ts].find(seq) == m_data[ts].end()){
            return -1;
        }else{
            memcpy(data + offset, &m_data[ts][seq][0], m_data[ts][seq].size());
        }
    }
}
